package com.anlogic.sdk.toolchain;

import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.logging.log4j.Logger;

import com.anlogic.sdk.utils.EnvUtils;
import com.anlogic.sdk.utils.LogUtils;

public class ToolchainProperty {
	private static Logger logger = LogUtils.getLogger(ToolchainProperty.class);
	
	private static final String PROPERTIES = Activator.PLUGIN_ID + ".toolchain";
	private static final String VARIABLE_ECLIPSE_HOME = "eclipse_home";
	private static final String VARIABLE_OS_TYPE = "os_type";

	private static Map<String, String> macroMap = new HashMap<String, String>();

	static {
		macroMap.put(VARIABLE_ECLIPSE_HOME, EnvUtils.getIDERootPath());
		macroMap.put(VARIABLE_OS_TYPE, EnvUtils.osType());
	}

	private static ResourceBundle RESOURCE_BUNDLE;

	static {
		try {
			RESOURCE_BUNDLE = ResourceBundle.getBundle(PROPERTIES);
		} catch (MissingResourceException e) {
			logger.error("Error to load toolchain property file");
		}
	}

	public static String getString(String key) {
		String ret = "";
		try {
			if (EnvUtils.isLinux()) {
				ret = fixToolchain(key);
			} else {
				ret = RESOURCE_BUNDLE.getString(key);
			}
			ret = resolveDynamicVariable(ret);
		} catch (MissingResourceException e) {
		}
		return ret;
	}

	public static String fixToolchain(String key) {
		String ret = "";
		if (key.equals("BUILD_TOOL_PATH")) {
			ret = RESOURCE_BUNDLE.getString("LINUX_BUILD_TOOL_PATH");
		} else {
			ret = RESOURCE_BUNDLE.getString(key);
		}

		return ret;
	}

	public static String resolveDynamicVariable(String input) {
		String output = input;
		if (input.indexOf("${") >= 0) {
			for (String key : macroMap.keySet()) {
				if (input.indexOf("${" + key + "}") >= 0) {
					output = output.replaceAll("[$][{]" + key + "[}]", macroMap.get(key));
					break;
				}
			}
		}
		return output;
	}
}
